package com.mender.gateway.filters;

import cn.hutool.core.text.AntPathMatcher;
import com.mender.common.constant.JwtClaimsConstant;
import com.mender.common.properties.JwtProperties;
import com.mender.common.utils.JwtUtil;
import com.mender.gateway.config.AuthProperties;
import io.jsonwebtoken.Claims;
import lombok.RequiredArgsConstructor;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * 登录校验过滤器
 */
@Component
@RequiredArgsConstructor
public class JwtTokenAdminGlobalFilter implements GlobalFilter, Ordered {

//    无需登录校验的路径
    private final AuthProperties authProperties;

//    jwt配置
    private final JwtProperties jwtProperties;

    private final AntPathMatcher antPathMatcher = new AntPathMatcher();
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
//        登录校验
        ServerHttpRequest request = exchange.getRequest();

        // 如果是 admin 接口才进
        if (!request.getPath().toString().startsWith("/admin")) {
            return chain.filter(exchange);
        }
//        判断是否需要拦截
        if (isExclude(request.getPath().toString())) {
            return chain.filter(exchange);
        }
        //        获取token
        String token = request.getHeaders().getFirst(jwtProperties.getAdminTokenName());
        //        校验token
        ServerHttpResponse response = exchange.getResponse();

        Long userId = null;
        try {
            Claims claims = JwtUtil.parseJWT(jwtProperties.getAdminSecretKey(), token);
            userId = Long.valueOf(claims.get(JwtClaimsConstant.EMP_ID).toString());
        } catch (Exception e) {
//            拦截
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        String userInfo = userId.toString();
//      传递用户id
        ServerWebExchange request1 = exchange.mutate()
                .request(builder -> builder.header("user-info", userInfo)).build();
        System.out.println("userId = " + userId);
        return chain.filter(request1);
    }

    /**
     * 判断是否需要拦截
     * @param path
     * @return
     */
    private boolean isExclude(String path) {
        for (String excludePath : authProperties.getExcludePaths()) {
            if (antPathMatcher.match(excludePath, path)) {
                return true;
            }
        }
        return false;
    }

    @Override
    public int getOrder() {
//        过滤器优先级
        return 0;
    }
}
